#include "Glow.h"
#include <sstream>
#include <iostream>
#include <cstdlib>

using namespace std;
using namespace glow;

int main(int argc, char **argv)
{
	int width = 800;
	int height = 600;
	bool fullscreen = false;
	if(argc >= 3)
	{
		width = atoi(argv[1]);
		height = atoi(argv[2]);
	}
	if(argc >= 4)
		fullscreen = true;
		
	// INITIALISATION
	GlowDevice *device = GlowDevice::getInstance();
	device->init(width, height, fullscreen);
	
	Renderer *rdr = device->getRenderer();
	EventManager *emgr = device->getEventManager();
	
	SkyBox sb;
	sb.load("../media/skybox/front.jpg",
		"../media/skybox/back.jpg",
		"../media/skybox/bottom.jpg",
		"../media/skybox/top.jpg",
		"../media/skybox/left.jpg",
		"../media/skybox/right.jpg");
	
	Camera c(Vector3d(0, 300, 0));
	c.setSensivity(1.0);
	c.setSpeed(30.0);
	
	// CHARGEMENT
	Mesh *moul = MeshFactory::create("../media/mouillere2.mnt");
	moul->genNormals();
	moul->setShininess(1.0);
	moul->setTexture("../media/mouillere2.png");
	
	Mesh *moulVA = MeshFactory::create("../media/mouillere2.mnt", false);
	moulVA->genNormals();
	moulVA->setShininess(1.0);
	moulVA->setTexture("../media/mouillere2.png");
	
	Light l1(GL_LIGHT0);
	l1.setPosition(Vector3f(512, 512, 230));
	l1.setDiffuse(Color4f(1.0, 1.0, 1.0));

	bool quit = false;
	bool show = false;
	bool drawNormals = false;
	bool useVBO = true;
	device->showCursor(show);
	
	// MAIN LOOP
	while(!emgr->quit() && !quit)
	{
		emgr->getEvent();
		c.getEvent();
		c.animate();
		sb.setPosition(c.getPosition());
		
		rdr->beginScene();
		c.look();
		sb.draw();
		l1.draw();

		l1.on();
		rdr->pushMatrix();
		rdr->rotate(-90,Vector3d(1.,0.,0.));
		if(useVBO)
			moul->draw();
		else
			moulVA->draw();
		l1.off();
		rdr->popMatrix();

		if(drawNormals)
		  {
		    rdr->pushMatrix();
		    rdr->translate(Vector3d(20, 5, 0));
		    rdr->rotate(-90,Vector3d(1.,0.,0.));
		    moul->drawNormals();
		    rdr->popMatrix();
		  }

		std::ostringstream oss;
		oss<<device->getFPS();
		std::string resultFPS = oss.str();
		
		device->setWindowTitle("DemoMNT Window | FPS : "+resultFPS);
		rdr->endScene();

		if(emgr->isKeyDownOnce(GLFW_KEY_ESC)) quit = true;
		if(emgr->isKeyDownOnce('B'))
		{
			show = !show;
			device->showCursor(show);
		}
		if(emgr->isKeyDownOnce('N')) drawNormals = !drawNormals;
		if(emgr->isKeyDownOnce('K')) rdr->setPolygonMode(GL_FRONT_AND_BACK, GL_POINT);
		if(emgr->isKeyDownOnce('L')) rdr->setPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
		if(emgr->isKeyDownOnce('M')) rdr->setPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
		if(emgr->isKeyDownOnce('V')) useVBO = !useVBO;
	}

	delete moul;
	delete moulVA;
	GlowDevice::destroy();
	
	return 0;
}
